package com.yili.oa.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yili.oa.entity.TableBase;
import com.yili.oa.entity.UserSearch;
import com.yili.oa.models.Role;
import com.yili.oa.models.User;
import com.yili.oa.service.RoleService;
import com.yili.oa.service.UserService;
import com.yili.oa.utils.Exception.AjaxException;
import com.yili.oa.vo.request.UserDataReq;
import com.yili.oa.vo.response.UserDataRes;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author lxr
 * @version v0.01
 * @date 2019/3/20 0020
 * @email 200890949@qq.com
 */
@SuppressWarnings("ALL")
@Controller
@RequestMapping("/sys/user")
public class UserApi {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;


    /**
     * 跳转到添加页面
     * @return
     */
    @RequestMapping("/addButton")
    public String addButton(ModelMap modelAndView){
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        List<Role> roles = roleService.getList(null);
        //如果不是超级管理员 不能添加超级管理员角色
        if (user.getUserRole()!=null) {
            Role role = roleService.getById(user.getUserRole());
            if (!role.getRoleKey().equals("superManager")){
                for (Role role1:
                        roles) {
                    if (role1.getRoleKey().equals("superManager")){
                        roles.remove(role1);
                    }
                }
            }
        }
        modelAndView.addAttribute("roles",roles);
        return "view/user/add";
    }

    /**
     * 添加用户
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public String add(UserDataReq userDataReq){
        if (StringUtils.isBlank(userDataReq.getUserId())) {
            if (StringUtils.isBlank(userDataReq.getUserAccount())) {
                throw new AjaxException("请输入用户名");
            } else {
                Boolean check = userService.checkAccount(userDataReq.getUserAccount(),null);
                if (!check) {
                    throw new AjaxException("该用户名已存在");
                }
            }
            //新增没填密码 默认密码
            if (StringUtils.isBlank(userDataReq.getUserPassword())) {
                //加密
                Object obj = new SimpleHash("MD5", "123456", null, 5);
                userDataReq.setUserPassword(obj.toString());
            }else {
                Object obj = new SimpleHash("MD5", userDataReq.getUserPassword(), null, 5);
                userDataReq.setUserPassword(obj.toString());
            }
            if (StringUtils.isBlank(userDataReq.getUserMobilePhone())) {
                throw new AjaxException("请输入手机号");
            }
            try {
                userService.add(userDataReq);
            } catch (Exception e) {
                return "error";
            }
        }else {
            if (userDataReq.getUserId().equals("0")){
                throw new AjaxException("超级管理员不能修改");
            }
            if (StringUtils.isBlank(userDataReq.getUserAccount())) {
                throw new AjaxException("请输入用户名");
            } else {
                Boolean check = userService.checkAccount(userDataReq.getUserAccount(),userDataReq.getUserId());
                if (!check) {
                    throw new AjaxException("该用户名已存在");
                }
            }
            if (StringUtils.isBlank(userDataReq.getUserMobilePhone())) {
                throw new AjaxException("请输入手机号");
            }
            //排除空串
            if (StringUtils.isBlank(userDataReq.getUserPassword())) {
                userDataReq.setUserPassword(null);
            }else {
                Object obj = new SimpleHash("MD5", userDataReq.getUserPassword(), null, 5);
                userDataReq.setUserPassword(obj.toString());
            }
            //排除空串
            if (StringUtils.isBlank(userDataReq.getUserApartment())) {
                userDataReq.setUserApartment(null);
            }
            userService.update(userDataReq);
        }
        return "success";
    }

    /**
     * 跳转到添加页面
     * @return
     */
    @GetMapping("/editButton/{userId}")
    public String editButton(@PathVariable("userId") String userId, ModelMap modelAndView){
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        if (StringUtils.isBlank(userId)){
            throw new AjaxException("该用户不存在");
        }
        List<Role> roles = roleService.getList(null);
        //如果不是超级管理员 不能添加超级管理员角色
        //只有有角色的人才能添加修改用户 所以不用判断是否有角色
        if (user.getUserRole()!=null) {
            Role role = roleService.getById(user.getUserRole());
            if (!role.getRoleKey().equals("superManager")){
                for (Role role1:
                        roles) {
                    if (role1.getRoleKey().equals("superManager")){
                        roles.remove(role1);
                    }
                }
            }
        }
        modelAndView.addAttribute("roles",roles);
        modelAndView.put("info", userService.getById(userId));
        return "view/user/add";
    }

    @PostMapping("/delete")
    @ResponseBody
    public Map<String,String> edit(@RequestBody String[] userIds) {
        Map<String, String> map = new HashMap<>();
        List<String> list = Arrays.asList(userIds);
        for (String id:
             list) {
            if (id.equals("0")){
                throw new AjaxException("超级管理员不能被删除");
            }
        }
        userService.del(list);
        map.put("success", "1");
        return map;
    }
    /**
     * 跳转登陆页面
     * @return
     */
//    @RequestMapping("/user")
//    public String login(){
//        return "/view/user";
//    }

    //

    /**
     * 获取用户列表数据
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    public TableBase userList(UserSearch search){
        User nowUser = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        PageHelper.startPage(search.getPage(),search.getLimit());
        if (search==null) {
            search = new UserSearch();
        }
        TableBase tableBase  = new TableBase();
        List<UserDataRes> list = new ArrayList<>();
        List<User> users = userService.searchUser(search);
        PageInfo pageInfo = new PageInfo<>(list,search.getLimit());
        for (User user:
                users) {
            //除了超级管理员其他都不能看到超级管理员账号
            //以后可以做从数据库就过滤
            if (user.getUserRole()!=null){
                Role role = roleService.getById(nowUser.getUserRole());
                if (!role.getRoleKey().equals("superManager")){
                    Role role1 = new Role();
                    role1=roleService.getById(user.getUserRole());
                    if (role1!=null){
                        if (role1.getRoleKey().equals("superManager")){
                            continue;
                        }
                    }
                }
            }
            UserDataRes udr = new UserDataRes();
            BeanUtils.copyProperties(user,udr);
            if (StringUtils.isNotBlank(user.getUserRole())){
                Role role = roleService.getById(user.getUserRole());
                if (role==null){
                    udr.setUserRoleName(null);
                    userService.updRole(user.getUserId());
                }else {
                    udr.setUserRoleName(role.getRoleName());
                }
            }
            if (StringUtils.isNotBlank(user.getUserCreateUser())){
                UserDataRes createUser = userService.getById(user.getUserCreateUser());
                udr.setUserCreateUser(createUser.getUserName());
            }
            if (StringUtils.isNotBlank(user.getUserUpdateUser())){
                UserDataRes updateUser = userService.getById(user.getUserUpdateUser());
                udr.setUserUpdateUser(updateUser.getUserName());
            }
            list.add(udr);
        }
        tableBase.setData(list);
        tableBase.setCode(0);
        tableBase.setMsg("");
        tableBase.setCount(pageInfo.getTotal());
        return tableBase;
    }
    /**
     * 状态按钮编辑
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public String edit(UserDataReq userDataReq){
        if (StringUtils.isBlank(userDataReq.getUserId())){
            throw new AjaxException("用户不存在");
        }
        if (StringUtils.isBlank(userDataReq.getUserStatus())){
            throw new AjaxException("状态为空");
        }
        Boolean result = userService.updStatus(userDataReq);
        if (!result){
            return "error";
        }
        return "success";
    }

    /**
     * 用户修改资料
     * @return
     */
    @GetMapping("/userEdit")
    public String userEditButton(ModelMap modelAndView){
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        if (user==null){
            return "login";
        }
        modelAndView.put("info", userService.getById(user.getUserId()));
        modelAndView.put("isUser","true");
        return "view/user/add";
    }
}
